package com.uduemc.biso.node.web.component.html;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.core.common.entities.SitePage;
import com.uduemc.biso.node.core.common.sysconfig.ProductSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.productsysconfig.ProductSysItemConfig;
import com.uduemc.biso.node.core.common.sysconfig.productsysconfig.ProductSysItemTextConfig;
import com.uduemc.biso.node.core.common.syspojo.ProductImageStyleDataList;
import com.uduemc.biso.node.core.common.udinpojo.common.ImageConfig;
import com.uduemc.biso.node.core.entities.*;
import com.uduemc.biso.node.core.entities.custom.Product;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.SProductPrevNext;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.SpringContextUtils;
import com.uduemc.biso.node.web.service.SRHeadService;
import com.uduemc.biso.node.web.service.byfeign.SystemService;
import com.uduemc.biso.node.web.service.html.HFormService;
import com.uduemc.biso.node.web.utils.IconClassUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HSystemProductItemUdin {

    private static final String name = "system_product_item";

    @Resource
    private BasicUdin basicUdin;

    @Resource
    private SiteUrlComponent siteUrlComponent;

    @Resource
    private RequestHolder requestHolder;

    @Resource
    private HFormService hFormServiceImpl;

    public StringBuilder html(SitePage sitePage, ProductSysConfig productSysConfig, Product product, long languageId, SProductPrevNext sProductPrevNext)
            throws IOException {
        if (productSysConfig == null) {
            return new StringBuilder("<!-- productSysConfig empty -->");
        }
        // 生成html渲染内容
        StringBuilder stringBuilder = new StringBuilder("<!-- product item page -->\n");

        // 制作 breadcrumbs 顶部面包屑这个部分
        String breadcrumbs = getBreadcrumbs(sitePage.getSPage(), sitePage.getSCategories(), product.getSProduct());

        // 制作 $imageHtml 图片
        String imageHtml = getImageHtml(productSysConfig, product.getListImageListInfo());

        // 制作$imageHtmlWap图片
        String imageHtmlWap = imageHtmlWap(product.getListImageListInfo());

        // htmlShare 和 htmlShareWap
        String htmlShare = htmlShare(product.getSProduct(), productSysConfig, languageId);
        String htmlShareWap = "";
        // 手机分享调用浏览器通用分享API 只支持HTTPS
        if ("https".equals(requestHolder.getRequest().getScheme())) {
            htmlShareWap = htmlShareWap(productSysConfig, languageId);
        }

        int structure = productSysConfig.getList().getStructure();

        // 渲染HTML的模板名称
        String styleFile = getStyleFile(productSysConfig);

        // 文件下载
        List<RepertoryQuote> listFileListInfo = product.getListFileListInfo();

        // 产品 label 部分HTML渲染内容 $productLabelHtml
        String productLabelHtml = productLabelHtml(productSysConfig, product.getListLabelContent(), listFileListInfo);

        Map<String, String> mapHtml = new HashMap<>();
        mapHtml.put("productLabelHtml", productLabelHtml);

        // 排序以及过滤
        List<String> sortProductFooterHtml = sortProductFooterHtml(productSysConfig, mapHtml);
        // 产品通过排序获得底部内容显示html
        String productFooterHtml = productFooterHtml(sitePage, productSysConfig, product, sortProductFooterHtml, sProductPrevNext);


        Map<String, Object> mapData = new HashMap<>();
        mapData.put("breadcrumbs", breadcrumbs);
        mapData.put("structure", structure);
        mapData.put("imageHtml", imageHtml);
        mapData.put("imageHtmlWap", imageHtmlWap);
        mapData.put("htmlShare", htmlShare);
        mapData.put("htmlShareWap", htmlShareWap);
        mapData.put("productLabelHtml", productLabelHtml);
        mapData.put("productFooterHtml", productFooterHtml);
        mapData.put("productInfo", filterProductHtml(product));
        StringWriter render = basicUdin.render(name, styleFile, mapData);
        stringBuilder.append(render);
        // 加入脚本
        stringBuilder.append("<script type=\"text/javascript\" src=\"").append(siteUrlComponent.getSourcePath("/assets/static/site/public/js/jquery.product_detail.js")).append("\"></script>");
        return stringBuilder;
    }

    protected String messageHtml(ProductSysConfig productSysConfig, SSystem sSystem, SProduct sProduct) throws IOException {
        ProductSysItemConfig itemConfig = productSysConfig.getItem();
        int showMessage = itemConfig.getShowMessage();
        if (showMessage != 1) {
            return "";
        }

        Long formId = sSystem.getFormId();
        if (formId == null || formId < 1) {
            return "";
        }

        // 写入 JavaScript 地址
        SRHeadService sRHeadServiceImpl = SpringContextUtils.getBean("sRHeadServiceImpl", SRHeadService.class);
        sRHeadServiceImpl.remakeform();

        ProductSysItemTextConfig itextConfig = productSysConfig.getItext();
        String messageText = itextConfig.getMessageText();

        StringBuilder html = hFormServiceImpl.html(sSystem, sProduct);

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("messageText", messageText);
        mapData.put("formHtml", html);
        StringWriter render = basicUdin.render(name, "message", mapData);
        return render.toString();
    }

    protected String makePrevNextHtml(SPage sPage, ProductSysConfig productSysConfig, SProductPrevNext sProductPrevNext) {
        ProductSysItemTextConfig itext = productSysConfig.getItext();
        String prevNextNoData = itext.getPrevNextNoData();
        String prevText = itext.getPrevText();
        String nextText = itext.getNextText();

        prevNextNoData = StrUtil.isNotBlank(prevNextNoData) ? HtmlUtils.htmlEscape(prevNextNoData) : "";
        prevText = StrUtil.isNotBlank(prevText) ? HtmlUtils.htmlEscape(prevText) : "";
        nextText = StrUtil.isNotBlank(nextText) ? HtmlUtils.htmlEscape(nextText) : "";

        SProduct prev = sProductPrevNext != null ? sProductPrevNext.getPrev() : null;
        SProduct next = sProductPrevNext != null ? sProductPrevNext.getNext() : null;

        String prevContent;
        if (prev == null) {
            prevContent = prevNextNoData;
        } else {
            String title = HtmlUtils.htmlEscape(prev.getTitle());
            SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
            SSystemItemCustomLink sSystemItemCustomLink = null;
            try {
                sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(prev.getHostId(), prev.getSiteId(), prev.getSystemId(), prev.getId());
            } catch (IOException e) {
                log.error("获取正常状态下的系统内容自定义链接数据失败：" + e.getMessage());
            }
            String articleHref = siteUrlComponent.getProductHref(sPage, prev, sSystemItemCustomLink);
            prevContent = "<a href=\"" + articleHref + "\" title=\"" + title + "\">" + title + "</a>";
        }

        String nextContent;
        if (next == null) {
            nextContent = prevNextNoData;
        } else {
            String title = HtmlUtils.htmlEscape(next.getTitle());
            SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
            SSystemItemCustomLink sSystemItemCustomLink = null;
            try {
                sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(next.getHostId(), next.getSiteId(), next.getSystemId(), next.getId());
            } catch (IOException e) {
                log.error("获取正常状态下的系统内容自定义链接数据失败：" + e.getMessage());
            }
            String articleHref = siteUrlComponent.getProductHref(sPage, next, sSystemItemCustomLink);
            nextContent = "<a href=\"" + articleHref + "\" title=\"" + title + "\">" + title + "</a>";
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("prevText", prevText);
        mapData.put("nextText", nextText);
        mapData.put("prevContent", prevContent);
        mapData.put("nextContent", nextContent);
        StringWriter render = basicUdin.render(name, "prevnext", mapData);
        return render.toString();
    }

    protected String htmlShareWap(ProductSysConfig productSysConfig, long languageId) {
        int showShare = productSysConfig.getItem().getShowShare();
        if (showShare != 1) {
            return "";
        }
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("languageId", languageId);   // 暂时没有使用
        StringWriter render = basicUdin.render(name, "html_share_wap", mapData);
        return render.toString();
    }

    protected String htmlShare(SProduct sProduct, ProductSysConfig productSysConfig, long languageId) {
        int showShare = productSysConfig.getItem().getShowShare();
        int showPriceString = productSysConfig.getItem().getShowPriceString();
        if (showShare != 1 && showPriceString != 1) {
            return "";
        }
        String priceString = StrUtil.isBlank(sProduct.getPriceString()) ? "" : HtmlUtils.htmlEscape(sProduct.getPriceString());
        String sharet = productSysConfig.getItext().getSharet();
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("showShare", showShare);
        mapData.put("showPriceString", showPriceString);
        mapData.put("languageId", languageId);   // 暂时没有使用

        mapData.put("sharet", sharet);
        mapData.put("priceString", priceString);
        StringWriter render = basicUdin.render(name, "html_share", mapData);
        return render.toString();
    }

    protected List<String> sortProductFooterHtml(ProductSysConfig productSysConfig, Map<String, String> mapHtml) {
        List<String> listHtml = new ArrayList<>();
        int style = productSysConfig.getItem().getStyle();
        for (Map.Entry<String, String> entry : mapHtml.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (key.equals("productLabelHtml") && (style == 4 || style == 5)) {
                continue;
            }
            listHtml.add(value);
        }
        return listHtml;
    }

    protected String productFileHtml(ProductSysConfig productSysConfig, List<RepertoryQuote> listFileListInfo) {
        if (CollUtil.isEmpty(listFileListInfo)) {
            return "";
        }


        List<Map<String, String>> fileList = new ArrayList<>();
        for (RepertoryQuote repertoryQuote : listFileListInfo) {
            HRepertory hRepertory = repertoryQuote.getHRepertory();

            Map<String, String> downFile = new HashMap<>();
            String filename = repertoryQuote.getHRepertory().getOriginalFilename();
            String downloadhref = siteUrlComponent.getDownloadHref(hRepertory.getId());
            String icon = IconClassUtil.systemItemDownload(hRepertory.getSuffix());

            String token = String.valueOf(hRepertory.getId());
            try {
                token = CryptoJava.en(token);
            } catch (Exception e) {
                log.error("加密hRepertory数据Id异常：" + e.getMessage());
            }

            String onlineBrowseHref = "javascript:void(0);";
            String suffix = hRepertory.getSuffix();
            if (StrUtil.isNotBlank(suffix) && suffix.equalsIgnoreCase("pdf")) {
                suffix = suffix.toLowerCase();
                onlineBrowseHref = siteUrlComponent.getPreviewPdfHref(filename, hRepertory.getId());
            }

            downFile.put("icon", icon);
            downFile.put("token", token);
            downFile.put("filename", filename);
            downFile.put("suffix", suffix);
            downFile.put("onlineBrowseHref", onlineBrowseHref);
            downFile.put("downloadhref", downloadhref);
            fileList.add(downFile);
        }

        ProductSysItemTextConfig itext = productSysConfig.getItext();
        String downLabel = itext.getDownLabel();
        String downText = itext.getDownText();
        String onlineBrowseText = itext.getOnlineBrowseText();

        downLabel = StrUtil.isNotBlank(downLabel) ? HtmlUtils.htmlEscape(downLabel) : "";
        downText = StrUtil.isNotBlank(downText) ? HtmlUtils.htmlEscape(downText) : "";
        onlineBrowseText = StrUtil.isNotBlank(onlineBrowseText) ? HtmlUtils.htmlEscape(onlineBrowseText) : "";

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("downLabel", downLabel);
        mapData.put("downText", downText);
        mapData.put("onlineBrowseText", onlineBrowseText);
        mapData.put("fileList", fileList);
        StringWriter render = basicUdin.render(name, "file/default", mapData);
        return render.toString();

    }

    protected String productFooterHtml(SitePage sitePage, ProductSysConfig productSysConfig, Product product, List<String> listHtml, SProductPrevNext sProductPrevNext) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        for (String value : listHtml) {
//			String key = iterator.next().getKey();
            stringBuilder.append(value);
        }


        // 产品留言
        String messageHtml = messageHtml(productSysConfig, sitePage.getSSystem(), product.getSProduct());
        stringBuilder.append(messageHtml);

        int prevNext = productSysConfig.getItem().getShowPrevNext();
        String prevNextHtml = prevNext == 1 ? makePrevNextHtml(sitePage.getSPage(), productSysConfig, sProductPrevNext) : "";

        // 其他部分，包含 product_others
        int showBackBtn = productSysConfig.getItem().getShowBackBtn();
        String returnt = HtmlUtils.htmlEscape(productSysConfig.getItext().getReturnt());
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("showBackBtn", showBackBtn);
        mapData.put("returnt", returnt);
        mapData.put("prevNextHtml", prevNextHtml);
        StringWriter render = basicUdin.render(name, "product_others", mapData);
        stringBuilder.append(render);
        return stringBuilder.toString();
    }

    protected String productLabelHtml(ProductSysConfig productSysConfig, List<SProductLabel> listLabelContent, List<RepertoryQuote> listFileListInfo) {
        if (CollectionUtils.isEmpty(listLabelContent)) {
            return "";
        }
        listLabelContent.forEach(item -> item.setTitle(HtmlUtils.htmlEscape(item.getTitle())));
        ProductSysItemConfig productSysItemConfig = productSysConfig.getItem();
        int showLabelTag = productSysItemConfig.getShowLabelTag();

        String productFileHtml = "";
        if (CollUtil.isNotEmpty(listFileListInfo)) {
            productFileHtml = productFileHtml(productSysConfig, listFileListInfo);
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("showLabelTag", showLabelTag);
        mapData.put("productLabel", listLabelContent);
        mapData.put("productFileHtml", productFileHtml);
        StringWriter render = basicUdin.render(name, "lable/default", mapData);
        return render.toString();
    }

    protected String imageHtmlWap(List<RepertoryQuote> listImageListInfo) {
        List<ProductImageStyleDataList> productImage = new ArrayList<>();
        if (!CollectionUtils.isEmpty(listImageListInfo)) {
            for (RepertoryQuote repertoryQuote : listImageListInfo) {
                HRepertory hRepertory = repertoryQuote.getHRepertory();
                SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();
                String src = siteUrlComponent.getImgEmptySrc();
                if (hRepertory != null) {
                    src = siteUrlComponent.getImgSrc(hRepertory);
                }
                String iTitle = "";
                String iAlt = "";
                if (sRepertoryQuote != null) {
                    String sRepertoryQuoteConfig = sRepertoryQuote.getConfig();
                    if (StringUtils.hasText(sRepertoryQuoteConfig)) {
                        ImageConfig imageConfig = ComponentUtil.getConfig(sRepertoryQuoteConfig, ImageConfig.class);
                        if (imageConfig != null) {
                            String imageConfigTitle = imageConfig.getTitle();
                            if (StringUtils.hasText(imageConfigTitle)) {
                                iTitle = HtmlUtils.htmlEscape(imageConfigTitle);
                            }
                            String imageConfigAlt = imageConfig.getAlt();
                            if (StringUtils.hasText(imageConfigAlt)) {
                                iAlt = HtmlUtils.htmlEscape(imageConfigAlt);
                            }
                        }
                    }
                }

                ProductImageStyleDataList productImageStyleDataList = new ProductImageStyleDataList();
                productImageStyleDataList.setAlt(iAlt).setTitle(iTitle).setSrc(src).setId(hRepertory != null ? hRepertory.getId() : 0L);

                productImage.add(productImageStyleDataList);
            }
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("productImage", productImage);
        mapData.put("srcPrefix", siteUrlComponent.prefix());
        StringWriter render = basicUdin.render(name, "image_default_wap", mapData);
        return render.toString();
    }

    protected String getImageHtml(ProductSysConfig productSysConfig, List<RepertoryQuote> listImageListInfo) {
        ProductSysItemConfig productSysItemConfig = productSysConfig.getItem();
        int style = productSysItemConfig.getStyle();
        int showZoom = productSysItemConfig.getShowZoom();
        String imageStyle;
        switch (style) {
            case 2:
                imageStyle = "image_style_2";
                break;
            case 3:
                imageStyle = "image_style_3";
                break;
            case 4:
                imageStyle = "image_style_4";
                break;
            case 5:
                imageStyle = "image_style_5";
                break;
            case 1:
            default:
                imageStyle = "image_style_1";
        }

        // 默认第一张图片
        ProductImageStyleDataList defaultImage = ProductImageStyleDataList.defaultProductImageStyleDataList();
        defaultImage.setSrc(siteUrlComponent.getImgEmptySrc());

        List<ProductImageStyleDataList> productImage = new ArrayList<>();
        if (!CollectionUtils.isEmpty(listImageListInfo)) {
            int i = 0;
            for (RepertoryQuote repertoryQuote : listImageListInfo) {
                HRepertory hRepertory = repertoryQuote.getHRepertory();
                SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();
                String src = siteUrlComponent.getImgEmptySrc();
                if (hRepertory != null) {
                    src = siteUrlComponent.getImgSrc(hRepertory);
                }
                String iTitle = "";
                String iAlt = "";
                if (sRepertoryQuote != null) {
                    String sRepertoryQuoteConfig = sRepertoryQuote.getConfig();
                    if (StringUtils.hasText(sRepertoryQuoteConfig)) {
                        ImageConfig imageConfig = ComponentUtil.getConfig(sRepertoryQuoteConfig, ImageConfig.class);
                        if (imageConfig != null) {
                            String imageConfigTitle = imageConfig.getTitle();
                            if (StringUtils.hasText(imageConfigTitle)) {
                                iTitle = HtmlUtils.htmlEscape(imageConfigTitle);
                            }
                            String imageConfigAlt = imageConfig.getAlt();
                            if (StringUtils.hasText(imageConfigAlt)) {
                                iAlt = HtmlUtils.htmlEscape(imageConfigAlt);
                            }
                        }
                    }
                }

                ProductImageStyleDataList productImageStyleDataList = new ProductImageStyleDataList();
                productImageStyleDataList.setAlt(iAlt).setTitle(iTitle).setSrc(src).setId(hRepertory != null ? hRepertory.getId() : 0);

                productImage.add(productImageStyleDataList);

                // 这里是设置默认图片的相关信息
                if (i++ == 0) {
                    defaultImage.setSrc(src).setAlt(iAlt).setTitle(iTitle).setId(hRepertory != null ? hRepertory.getId() : 0);
                }
            }
        }

        if (showZoom == 1) {
            defaultImage.setZoom("true");
        } else {
            defaultImage.setZoom("false");
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("defaultImage", defaultImage);
        mapData.put("productImage", productImage);
        mapData.put("srcPrefix", siteUrlComponent.prefix());
        StringWriter render = basicUdin.render(name, imageStyle, mapData);
        return render.toString();
    }

    /**
     * 生成顶部产品面包屑
     *
     * @param sPage       页面数据
     * @param sCategories 分类数据
     * @param sProduct    产品数据
     * @return 面包屑 html
     */
    protected String getBreadcrumbs(SPage sPage, SCategories sCategories, SProduct sProduct) {
        StringBuilder stringBuilder = new StringBuilder();

        String pageName = sPage.getName();
        String pageHref = siteUrlComponent.getPageHref(sPage);
        stringBuilder.append("<div class=\"w-breadcrumbs\"><a href=\"").append(pageHref).append("\">").append(pageName).append("</a> > ");

        if (sCategories != null) {
            String categoryName = sCategories.getName();
            String categoryHref = siteUrlComponent.getCategoryHref(sPage, sCategories);
            stringBuilder.append("<a href=\"").append(categoryHref).append("\">").append(categoryName).append("</a> > ");
        }

        String title = sProduct.getTitle();
        stringBuilder.append("<span>").append(title).append("</span> </div>");

        return stringBuilder.toString();
    }

    public static String getStyleFile(ProductSysConfig productSysConfig) {
        ProductSysItemConfig productSysItemConfig = productSysConfig.getItem();
        int style = productSysItemConfig.getStyle();
        String styleFile;
        switch (style) {
            case 2:
                styleFile = "default_2";
                break;
            case 3:
                styleFile = "default_3";
                break;
            case 4:
                styleFile = "default_4";
                break;
            case 5:
                styleFile = "default_5";
                break;
            case 1:
            default:
                styleFile = "default_1";
        }
        return styleFile;
    }

    /**
     * 过滤SProduct 的 htmlEscape 部分
     *
     * @param product 产品数据
     * @return 返回产品简介过滤后的 SProduct 产品数据
     */
    protected static SProduct filterProductHtml(Product product) {
        SProduct sProduct = product.getSProduct();
        String info = HtmlUtils.htmlEscape(sProduct.getInfo());
        info = info.replaceAll("\\n", "<br/>");
//		info = info.replaceAll("\\s", "&nbsp;");
        sProduct.setTitle(HtmlUtils.htmlEscape(sProduct.getTitle())).setInfo(info);
        return sProduct;
    }
}
